package dome1;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int value) {
            this.val = value;
        }
    }
    public TreeNode root;
    public boolean search(int val) {
        TreeNode cur = root;
        while(cur!=null) {
            if(cur.val < val) {
                cur = cur.right;
            }else if(cur.val > val) {
                cur = cur.left;
            }else {
                return true;
            }
        }
        return false;
    }

    //O(logN)
    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return;
        }
        TreeNode parent = null;
        TreeNode cur = root;
        while(cur!=null) {
            parent = cur;
            if(val < cur.val) {
                cur = cur.left;
            }else if(val > cur.val) {
                cur = cur.right;
            }else {
                return;
            }
        }
        if(val < parent.val) {
            parent.left = node;
        }else {
            parent.right = node;
        }
    }

    public void remove(int val) {
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null) {
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                removeNode(parent,cur);
                return;
            }
        }
    }

    private void removeNode(TreeNode parent, TreeNode cur) {
        if(cur.left == null) {
            if(cur == root) {
                root = root.right;
            }
            if(parent.left == cur) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = root.left;
            }
            if(parent.left == cur) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            //cur   左树的最大值  或  右树的最小值
            TreeNode traget = cur.left;
            TreeNode tragetParent = null;
            while(traget.right!=null) {
                tragetParent = traget;
                traget = traget.right;
            }
            cur.val = traget.val;
            if(tragetParent.right == traget) {
                tragetParent.right = traget.left;
            }else {
                tragetParent.left = traget.left;
            }
        }
    }
}














